<?php

namespace app\index\controller;

use app\common\model\FruitModel;
use app\common\model\FruitTypeModel;
use app\common\model\MemberModel;
use app\common\model\TeacherModel;
use app\index\validate\Fruit;
use think\Db;

class FruitController extends BaseController
{
    public function index()
    {
        $keyword = $this->request->param('keyword');
        $college_id = $this->request->param('college_id');
        $page = $this->request->param('page') ? $this->request->param('page') : 1;
        if ($keyword){
            if ($college_id){
                $count = Db::query("select count(*) as count from sk_fruit where college = ".$college_id." and (title like '%".$keyword."%' or keywords like '%".$keyword."%') limit 1");
                $fruits = Db::query("select * from sk_fruit where college = ".$college_id." and (title like '%".$keyword."%' or keywords like '%".$keyword."%') order by create_time desc limit ".($page -1)*10 . ",10");
                $count = $count[0]['count'];
            }else{
                $count = FruitModel::where('title','like','%'.$keyword.'%')->whereOr('keywords','like','%'.$keyword.'%')->count();
                $fruits = FruitModel::where('title','like','%'.$keyword.'%')
                    ->whereOr('keywords','like','%'.$keyword.'%')
                    ->order('create_time desc')
                    ->page($page,10)
                    ->all();
            }
        }else{

            if ($college_id){
                $count = FruitModel::where('status', 1)->where('college',$college_id)->count();
                $fruits = FruitModel::with(['teacher', 'member'])->where('status', 1)->where('college',$college_id)
                    ->order('create_time desc')
                    ->page($page, 10)
                    ->all();
            }else{
                $count = FruitModel::where('status', 1)->count();
                $fruits = FruitModel::with(['teacher', 'member'])->where('status', 1)
                    ->order('create_time desc')
                    ->page($page, 10)
                    ->all();
            }

        }
        $n_fruits = FruitModel::where('status', 1)
            ->order('id desc')
            ->limit(0, 8)
            ->all();
        foreach ($fruits as $key => $vo) {
            if (isset($vo['teacher'])){
                $fruits[$key]['user'] =  $vo['teacher'];
            }else{
                $fruits[$key]['user'] =  TeacherModel::get($vo['issuer']);
            }
        }
        $this->assign(['count' => $count, 'fruits' => $fruits, 'page' => $page, 'maxPage' => ceil($count / 10), 'n_fruits' => $n_fruits, 'keyword' => $keyword, 'college_id' => $college_id]);//,'slide'=>$slide

        if (is_mobile()){
            return $this->fetch('/mobile/fruit/index');
            }

        return $this->fetch();
    }

    public function detail()
    {
        $id = $this->request->param("id");
        if (!$id) {
            $this->redirect("index");
        } else {

            $this->checkLogin();
            $fruit = FruitModel::where('id', $id)->find();
            $user = json_decode(session('userInfo'),true);

            if ($user){
                $issuer_type = isset($user['teacher_no']) ? 0 : 1;
                $collection = Db::name('collection')->where('type',1)->where('cid',$id)->where('uid',$user['id'])->where('user_type',$issuer_type)->find();
                $this->assign('collection',$collection);
            }


            $issuer = null;
            if ($fruit['issuer_type'] == 0) {
                $issuer = TeacherModel::where('id', $fruit['issuer'])->find();
            } else {
                $issuer = MemberModel::where('id', $fruit['issuer'])->find();
            }
            $fruit['content'] = htmlspecialchars_decode($fruit['content']);
            $this->assign('fruit', $fruit);
            $this->assign('issuer', $issuer);
            FruitModel::where('id',$fruit['id'])->setInc('hits',1);
        }

        if (is_mobile()){
            return $this->fetch('/mobile/fruit/detail');
        }

        return $this->fetch();
    }
    public function adminDetail()
    {
        $id = $this->request->param("id");
        if (!$id) {
            $this->redirect("index");
        } else {

            if (!session('ADMIN_ID')){
                $this->checkLogin();
            }
            $fruit = FruitModel::where('id', $id)->find();
            $user = json_decode(session('userInfo'),true);

            if ($user){
                $issuer_type = isset($user['teacher_no']) ? 0 : 1;
                $collection = Db::name('collection')->where('type',1)->where('cid',$id)->where('uid',$user['id'])->where('user_type',$issuer_type)->find();
                $this->assign('collection',$collection);
            }


            $issuer = null;
            if ($fruit['issuer_type'] == 0) {
                $issuer = TeacherModel::where('id', $fruit['issuer'])->find();
            } else {
                $issuer = MemberModel::where('id', $fruit['issuer'])->find();
            }
            $fruit['content'] = htmlspecialchars_decode($fruit['content']);
            $this->assign('fruit', $fruit);
            $this->assign('issuer', $issuer);
            $this->assign('isAdmin', session('ADMIN_ID'));
            FruitModel::where('id',$fruit['id'])->setInc('hits',1);
        }


        return $this->fetch('detail');
    }

    public function publish()
    {
        if (!session('uid')){
            return $this->error('请先登录','login/login');
        }
        $id = $this->request->param("id");
        if ($id){
            $fruit = FruitModel::where('id',$id)->find();
            $fruit['content']  =  htmlspecialchars_decode($fruit['content']);
            $fruitType = FruitTypeModel::all();
            $this->assign([
               'fruit' => $fruit,
               'fruit_type' => $fruitType,
            ]);
        }else{
            $fruitType = FruitTypeModel::all();
            $this->assign([
                'fruit' => null,
                'fruit_type' => $fruitType,
            ]);
        }
        return $this->fetch();
    }

    public function save()
    {
        if ($this->request->isPost()) {
            $user = json_decode(session('userInfo'),true);
            if (isset($user['teacher_no'])) {
                $param = $this->request->param();


                $validate = new Fruit();
                if (!$validate->check($param)) {
                    $res['code'] = 0;
                    $res['msg'] = $validate->getError();
                    return $res;
                }

                $id = isset($param['id'])?$param['id']:null;
                if ($_FILES["file"]["error"] == 0) {
                    $file = $this->request->file('file');
                    $path = "file";
                    $info = $file->validate(['size' => 10485760, 'ext' => 'pdf,doc,docx,txt'])->rule('uniqid')->move('../public/upload/file/');
                    if ($info) {
                        $fileInfo = $info->getInfo();
                        $res['name'] = $fileInfo['name'];
                        $res['filepath'] = '/upload/file/' . $info->getSaveName();
                        Db::name('asset')->insert(['path' => $path, 'file_name' => $fileInfo['name'], 'type' => $fileInfo['type'], 'size' => $fileInfo['size'], 'file_path' => '/upload/file/' . $info->getSaveName()]);

                        $data['path'] = '/upload/file/' . $info->getSaveName();
                        $size = $fileInfo['size'];
                        if ($size > 1024) {
                            $lastsize = intval($size / 1024) . 'KB';
                        }
                        if (($size / 1024) > 1024) {
                            $lastsize = intval($size / 1048576) . 'MB';
                        }
                        $downdata = array(
                            'title' => $fileInfo['name'],
                            'type' => $fileInfo['type'],
                            'size' => $lastsize,
                            'src' => $data['path'],
                            'time' => time(),
                        );
                        $param['file_name'] = $fileInfo['name'];
                        $param['attachment'] = $data['path'];

                        if ($id){
                            $fruit = FruitModel::where('id',$id)->find();
                            $oldPath = $fruit['attachment'];
                            if (!empty($oldPath) && file_exists(ROOT_PATH.$oldPath)){
                                Db::name('asset')->where('path',$oldPath)->delete();
                                unlink(ROOT_PATH.$oldPath);
                            }
                        }
                    } else {
                        return [
                            'code' => 0,
                            'msg' => '文件过大或类型不支持'
                        ];
                    }
                }
            }else{
                return [
                    'code' => 0,
                    'msg' => '普通用户无法发布成果'
                ];
            }

            $param['issuer'] = $user['id'];
            $param['update_time'] = date('Y-m-d H:i:s',time());
            $param['college'] = $user['college'];
            unset($param['id']);
            if ($id){
                $param['status'] = 0;
                $result = FruitModel::where('id',$id)->update($param);
                if ($result !== false){
                    return [
                        'code' => 1,
                        'msg' => '更新成功'
                    ];
                }else{
                    return [
                        'code' => 0,
                        'msg' => '普通用户无法发布成果'
                    ];
                }
            }else{
                $insert = FruitModel::insert($param);

                if ($insert !== false){
                    $count = get_option('fruit_count');
                    if ($count){
                        set_option('fruit_count',['count'=>( $count['count']+1)]);
                    }else{
                        set_option('fruit_count',['count'=>1]);
                    }

                    return [
                        'code' => 1,
                        'msg' => '发布成功,等待审核'
                    ];
                }else{
                    return [
                        'code' => 0,
                        'msg' => '发布失败,请重试'
                    ];
                }
            }
        }
    }

    public function deleteFile(){
        if ($this->request->isPost()) {
            $user = json_decode(session('userInfo'), true);
            if (isset($user['teacher_no'])) {
                $param = $this->request->param();
                $id = isset($param['id']) ? $param['id'] : null;

                $fruit = FruitModel::where('id',$id)->find();
                $oldPath = $fruit['attachment'];
                FruitModel::where('id',$id)->update(['file_name'=>'','attachment'=>'']);
                if (file_exists(ROOT_PATH.$oldPath)){
                    Db::name('asset')->where('path',$oldPath)->delete();
                    unlink(ROOT_PATH.$oldPath);
                    return [
                        'code' => 1,
                        'msg' => '删除成功'
                    ];
                }else{
                    return [
                        'code' => 0,
                        'msg' => '删除失败'
                    ];
                }
            }else{
                return [
                    'code' => 0,
                    'msg' => '删除失败'
                ];
            }
        }
    }

    public function talentsDetail()
    {
        return $this->fetch();
    }

    public function downloadFile(){
        $id = $this->request->param('id');
        if ($id){
            $fruit = FruitModel::where('id',$id)->find();
            if ($fruit && $fruit['attachment']){
                $file_name = $fruit['file_name'];
                if (file_exists(ROOT_PATH.$fruit['attachment'])){
                    $file_path = ROOT_PATH.$fruit['attachment'];
                    $file = fopen ( $file_path, "rb" );
                    //告诉浏览器这是一个文件流格式的文件
                    Header ( "Content-type: application/octet-stream" );
                    //请求范围的度量单位
                    Header ( "Accept-Ranges: bytes" );
                    //Content-Length是指定包含于请求或响应中数据的字节长度
                    Header ( "Accept-Length: " . filesize ( $file_path ) );
                    //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
                    Header ( "Content-Disposition: attachment; filename=" . $file_name );
                    //读取文件内容并直接输出到浏览器
                    echo fread ( $file, filesize ( $file_path ) );
                    fclose ( $file );
                    exit ();

                }else{
                    return $this->error('无效的地址1');
                }
            }else{
                return $this->error('无效的地址2');
            }
        }else{
            return $this->error('无效的地址3');
        }
    }
}
